<template>
	<div class="vue_app NewThematicActivities" style="height: 100%;">
		<div class="sbbjclass">
			<m-header :title="Title" :hasTitle="true" :hasBack="true" :hasCart="true" v-show="isShare != 1">
				<Share :url="shareUrl()" style="right: 3rem;z-index: 100;"></Share>
			</m-header>
			<div style="z-index: 3">
				<animate-refresh @dataRefresh="dataRefresh" ref="animatexl">
				</animate-refresh>
			</div>
			<!---->
				<tab-head
					v-for="(item, index) in getRealComponentsList[0][0]"
					v-if="item.config.hasOwnProperty('clicktabbgcolor')"
					:key="index"
					:tabshow="!tabshow"
					:tabindex="tabindex" 				
					:titleInfor="HeaderTabNavArray" 
					@tabOnChange="tabOnChange"
					:config="item">
				</tab-head>

			<div class="contentnew" ref="scollAllClass" id="scollAllClass" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
				<div :style="`background-color: ${Bgcolor}`">
					<header-container style="position: relative;">
						<component 
							v-for="(item, index) in getRealComponentsList[0][0]" 
							v-sdrag="{componentName: item.componentName, handleType: 'sort', index}" 
							:is="item.componentName" 
							:key="index" 
							:config="item" 
							:data-id="item.id" 
							:dataList="dataStore[item.componentName][item.id]" 
							:copolddataobj="copolddata" 
							:part="0" 
							:tabindex="tabindex" 
							:titleInfor="HeaderTabNavArray" 
							@tabOnChange="tabOnChange"
							:tabshow="tabshow"
							>
				        </component>
					</header-container>

					<content-container>
						<component 
							v-for="(item, index) in getRealComponentsList[0][1]" 
							v-sdrag="{componentName: item.componentName, handleType: 'sort', index}" 
							:is="item.componentName" 
							:key="index" 
							:config="item" 
							:data-id="item.id" 
							:dataList="dataStore[item.componentName][item.id]" 
							:copolddataobj="copolddata" 
							:part="1" 
							:tabindex="tabindex" 
							:titleInfor="HeaderTabNavArray" 
							@tabOnChange="tabOnChange">
				        </component>
					</content-container>
				</div>
			</div>
		</div>
		<add-cart-animate></add-cart-animate>
	</div>
</template>
<script>
	//引用包裹“真实-基础组件”的组件
	import HeaderContainer from "../../real-components/HeaderContainer";
	import ContentContainer from "../../real-components/ContentContainer";
	import TabHead from "../../real-components/TabHead/_index";
	import AddCartAnimate from "../../real-components/AddCartAnimate";
	import AnimateRefresh from "@/real-components/AnimateRefreshPull";
    import Header from "../header";
	//引用真实-基础组件
	import UserCard from "../../real-components/UserCard/_index";
	import NewZone from "../../real-components/NewZone/_index";
	import GuessYouLike from "../../real-components/GuessYouLike/_index";
	import HomeCarousel from "../../real-components/HomeCarousel/_index";
	import activitiesbanner from "../../real-components/activitiesbanner/_index";
	import activitiesThreePic from "../../real-components/activitiesThreePic/_index";
	import activitiesSlidePic from "../../real-components/activitiesSlidePic/_index";
	import activitiesTwoPro from "../../real-components/activitiesTwoPro/_index";
	import activitiesOnePro from "../../real-components/activitiesOnePro/_index";
	import activitiesNinePro from "../../real-components/activitiesNinePro/_index";
	import ActivitieCoupons from "../../real-components/ActivitieCoupons/_index";
	import ActivitieCoupons2 from "../../real-components/ActivitieCoupons2/_index";
	//引用util文件
	import getPageName from "../../utils/getPageName";
	import axios from "axios";
	import initData, {baseComponentNames} from "../../utils/lxn/handleData";
	import { mapGetters, mapMutations } from "vuex";
	import Bscroll from 'better-scroll';
	import Share from "../../real-components/Share";
	export default {
		data() {
			return {
				Bgcolor: "",
				Title: "",
				//滑动页面
				tabshow: false,
				toscrolltop: "",
				puttDownY: 0,
				colwidth: '',
				tabcolwidth: '',
				tabindex: '',
				//兼容手机滑动
				Scrollphone: true,
				top: null,
				//动态获取head的高
				headheight: '',
				/*滑动的tab值*/
				Scrolltabindex: '',
				noclicktab: true,
				 //判断是否为分享的页面
				isShare: 0,
				//优惠券的实时更新信息
				copolddata: {},
				//下拉刷新的信息
				statY: 0,
				statX: 0,
				touchTime: 0,
				touchEndTop: false,
				isTop: true,
				flagfresh: true,
				//tab点击不触发滑动
				clicktabnoscoll: true,
				//最后一个tab滑动事件触发一次
				tabscollone:true,
				Asss:0
			}
		},
		components: {
			"m-header": Header,
			"header-container": HeaderContainer,
			ContentContainer,
			AddCartAnimate,
			AnimateRefresh,
			Share,
			"TabHead": TabHead,
			HomeCarousel,
			GuessYouLike,
			UserCard,
			NewZone,
			"activitiesbanner":activitiesbanner,
			"activitiesThreePic":activitiesThreePic,
			"activitiesSlidePic":activitiesSlidePic,
			"activitiesTwoPro":activitiesTwoPro,
			"activitiesNinePro":activitiesNinePro,
			"activitiesOnePro":activitiesOnePro,
			"ActivitieCoupons":ActivitieCoupons,
			"ActivitieCoupons2":ActivitieCoupons2,
			
		},
		computed: {
			...mapGetters('xxy', [
				"getacttabindex",
			]),
			...mapGetters("gw", [
				"getRealComponentsList"
			]),
			...mapGetters('xxy', {
				dataStore: "getDataStore"
			}),
			pageName() {
				return getPageName();
			},
			pageConfig() {
				return this.$store.getters['gw/getRealComponentsList']
			},
			pageComid() {
				let pageTree1 = this.getRealComponentsList[0][0] || [];
				let pageTree2 = this.getRealComponentsList[0][1] || [];
				for(var i = 0; i < pageTree1.length; i++) {
					if(pageTree1[i].componentName === 'TabHead' &&  pageTree1[i].config && pageTree1[i].config.pages) {
						return pageTree1[i].config.pages
					}
				}
				for(var j = 0; j < pageTree2.length; j++) {
					if(pageTree2[j].componentName === 'TabHead' && pageTree2[j].config && pageTree2[j].config.pages) {
						return pageTree2[j].config.pages
					}
				}
				return []
			},
			HeaderTabNavArray() {
				let pageTree1 = this.getRealComponentsList[0][0] || [];
				let pageTree2 = this.getRealComponentsList[0][1] || [];
				for(var i = 0; i < pageTree1.length; i++) {
					if(pageTree1[i].componentName === 'TabHead' &&  pageTree1[i].config && pageTree1[i].config.pages) {
						let arr = pageTree1[i].config.pages.filter(item => {
							return item.state === "1";
						}).map(item => {
							return {
								goodsClassName: item.name
							};
						});
						return arr;
					}
				}
				for(var j = 0; j < pageTree2.length; j++) {
					if(pageTree2[j].componentName === 'TabHead' && pageTree2[j].config && pageTree2[j].config.pages) {
						let arr = pageTree2[j].config.pages.filter(item => {
							return item.state === "1";
						}).map(item => {
							return {
								goodsClassName: item.name
							};
						});
						return arr;
					}
				}
				return []
			},
			env() {
				return window.environment;
			},
			scrollTop() {
				return this.$store.state.cjy.pagePosY
			},
			hasTabHeader() {
				let exits = false;
				let headerComponentsList = this.getRealComponentsList[0][0];//拿到头部组件列表
				for (let item of headerComponentsList) {
					if (item.componentName === "TabHead") {
						exits = true;
						break;
					}
				}
				return exits;
			}
		},
		methods: {
			...mapMutations('xxy', [
				"setstoptouch"
			]),
			//滚动事件
			createdScroll() {
				if(this.env === "edit") {
					this.getbannershow()
					return
				}
				// 如果bscroll实例存在那么就先销毁实例
				this.Bscroll && this.Bscroll.destroy()
				//拿到dom元素
				var verticalScroll = this.$refs.scollAllClass
				// 初始化实例
				this.Bscroll = new Bscroll(verticalScroll, {
					scrollY: true,
					click: true,
					bounce: false,
					swipeBounceTime: 2000,
					deceleration: 0.0015,
					freeScroll: true,
					momentum: true,
					probeType: 3,
					mouseWheel: true,
				})
				this.content = document.querySelector("#content-container");
				this.Bscroll.on("scroll", (pos) => {
					// console.log("1111111",pos)
					this.Asss = pos.y
					if (!this.hasTabHeader) return;//如果没有TabHeader组件终止
					this.scolllocation(pos)
					//实现第一部分功能
					if(document.querySelector(".tabzindex1")) {
						var tabHeight = window.getComputedStyle(document.querySelector(".tabzindex1"), null).height
						var bigheadHeight = window.getComputedStyle(document.querySelector("#header-container"), null).height
						if(this.isShare != 1) {
							var headerHeight = window.getComputedStyle(document.querySelector(".headerRight"), null).height
							if(headerHeight && headerHeight.indexOf('px') > -1) {
								var str = headerHeight.split("p")
							}
						}
						if(tabHeight && tabHeight.indexOf('px') > -1) {
							var str2 = tabHeight.split("p")
						}
						if(bigheadHeight && bigheadHeight.indexOf('px') > -1) {
							var str3 = bigheadHeight.split("p")
						}
						
						if(this.isShare == 1) {
							this.top = this.content.getBoundingClientRect().top - str2[0];
						} else {
							this.top = this.content.getBoundingClientRect().top - str[0] - str2[0];
						}
						var bannerHeight = str3[0] - str2[0]
						if(this.top < 0) {
							this.tabshow = true
						} else if(this.top > 0) {
							if(!this.Scrollphone) {
								this.Scrollphone = true;
								return
							} else if(this.Scrollphone) {
								this.tabshow = false;
							}
						}
					}
					//实现第二部分功能
					if(!this.clicktabnoscoll) {
						this.clicktabnoscoll = true
						return
					}
					if(document.querySelector(`div[data-id=${this.pageComid[0].comId}]`) && document.querySelector(`div[data-id=${this.pageComid[0].comId}]`).getBoundingClientRect().top - str[0] - str2[0] < 0) {
						var numlength = this.pageComid.length - 1
						this.noclicktab = true
						for(var i = 0; i < this.pageComid.length; i++) {
							if(document.querySelector(`div[data-id=${this.pageComid[i].comId}]`).getBoundingClientRect().top - str[0] - str2[0] > 0) {
								this.tabscollone = true
								if(this.Scrolltabindex == i - 1) {
									this.noclicktab = true
									return
								} else {
									this.noclicktab = false
									this.tabindex = (i - 1) + ''
									this.Scrolltabindex = (i - 1)
									return
								}
							} else if(this.tabscollone && document.querySelector(`div[data-id=${this.pageComid[numlength].comId}]`).getBoundingClientRect().top - str[0] - str2[0] < 0) {
								this.noclicktab = false
								this.tabindex = this.pageComid.length - 1 + ''
								this.Scrolltabindex = (this.pageComid.length - 1)
								this.tabscollone = false
								return
							}
						}
					}
				})
			},
			//跳转回调
			tabOnChange(index) {
				if(!this.noclicktab) {
					return
				}
				this.tabindex = index + ''
				if(this.tabindex > -1) {
					this.tabshow = true
				}
				let comId
				if(this.pageComid[index]) {
					comId = this.pageComid[index].comId
				}
				let element = document.querySelector(`div[data-id=${comId}]`)
				if(element) {
					setTimeout(() => {
						this.Bscroll.scrollToElement(element, 300);
						this.Scrollphone = false;
						this.clicktabnoscoll = false
					}, 10)
					this.Bscroll.on('scrollEnd', (pos) => {
						this.scolllocation(this.Bscroll)
					})
				}
			},
			getsessionIddata() {
				this.sessionIddata = localStorage.getItem('sessionId');
				this.storeCodedata = localStorage.getItem('storeCode');
				if(this.pageConfig[1]) {
					this.Bgcolor = this.pageConfig[1].activitiesBgcolor;
					this.Title = this.pageConfig[1].activitiesTitle;
				}
			},
			//优惠券信息对比
			queryCoupons3() {
				var sessionId = localStorage.getItem('sessionId');
				let url = api.trade_host + '/marketCenter/getDiffReleasedCoupons/' + api.enterpriseCode;
				let config = {
					url: url,
					method: 'GET',
					headers: {
						'sessionId': sessionId,
					},
				};
				axios(config).then((res) => {
					this.copolddata = res.data.data[0]
				})
			},
			//初始化监听数据变化
			inite() {
				PSEvent.listen("changeStoreCode", () => {
					this.getsessionIddata()
					this.getactData(true);
				});
				PSEvent.listen("BgcolorUpdate", () => {
					this.getsessionIddata()
				});
			},
			removeListen() {
				PSEvent.remove("changeStoreCode");
				PSEvent.remove("BgcolorUpdate");
				PSEvent.remove("dataRefresh", this.dataRefresh);
			},
			//分享链接
			shareUrl() {
				return `${location.href}?share=1`;
			},
			//滚动到指定位置  该方法会在3内秒持续调用 直到页面高度超过要到的页面位置
			gotoPosition(pos) {
				var position = pos // 跳转到的位置
				console.log("position11",position)
				if(position == 0) {
					this.$store.commit("cjy/SET_IS_RETURN", false)
				}
				var deleat = 100; //延迟时间
				var i = 0 // 执行次数
				var gotoPosistion = () => {
					i++ // 每次gotoPosistion执行次数加1
					// 设置定时器
					this.setTimeOut = setTimeout(() => {
						var bigheadHeight2 = window.getComputedStyle(document.querySelector("#header-container"), null).height
						if(bigheadHeight2 && bigheadHeight2.indexOf('px') > -1) {
							this.headheight = bigheadHeight2.split("p")[0]
						}
						var outerHeight = this.Bscroll ? -this.Bscroll.maxScrollY : 0 // 获取当前Bscroll的最大高度
						if(i * deleat > 3000) {
							//当执行到3000 ms时结束
							this.$store.commit("cjy/SET_IS_RETURN", false);
							this.isTop = true
							return
						} else if(outerHeight >= position) {
							if(pos > this.headheight) {
								this.tabshow = true
								this.tabindex = this.getacttabindex
								this.noclicktab = false
								this.$store.commit('xxy/setacttabindex', '');
								setTimeout(()=>{
									this.noclicktab = true
								},200)
							}
							// 当Bscroll的最大高度 不小于要滚动的位置 执行滚动到指定位置
							this.Bscroll.scrollTo(0, -position, 0, 'easing') // 让bscroll调到指定的位置
							this.scrollY = position // 将页面位置记录保存到组件
							this.$store.commit('cjy/CHANGE_PAGE_POS_Y', position) // 将页面位置存到vuex
							this.$store.commit("cjy/SET_IS_RETURN", false); // 将返回跳转状态重置
							this.isTop = false
							return
						}
						gotoPosistion() // 递归重复执行
					}, deleat)
				}

				//如果滚动位置为0 不需要混动 退出
				if(position == 0) {
					this.isTop = true
					return
				} else {
					this.isTop = false
				}
				gotoPosistion() //执行 跳转代码
			},

			//滑动事件开始
			touchStart(event) {
				this.setstoptouch(false)
				this.statY = event.changedTouches[0].clientY //
				this.statX = event.changedTouches[0].clientX
				// this.touchTime = 0
				this.Asss ===0 ?this.touchTime = 0:this.toushTime = this.$store.getters["lxn/getPagePositionY"]
				this.touchEndTop = false
			},

			// 手指滑动中
			touchMove(event) {
				// console.log("手指aaaa",event)
				// console.log("手指滑动1")
				var statMove = event.changedTouches[0].clientY // 手指相对屏幕的位置
				var puttDownY = Math.max(0, statMove - this.statY) //相对滑动开始时的手指距离
				this.puttDownY = puttDownY
				// console.log("a",statMove,this.statY)
				// console.log("b",this.isTop)
				// console.log("是不是true",statMove - this.statY > 0)
				// console.log("touchTime",this.touchTime)
				// console.log("是不是true",this.isTop)
				// console.log("statMove",statMove)
				if(statMove - this.statY > 0 && this.touchTime == 0 && this.isTop) {
					// console.log("手指滑动2")
					var touchPos = this.touchPos
					var isDown = Math.abs(event.changedTouches[0].clientY - this.statY) > Math.abs(event.changedTouches[0].clientX - this.statX)
					console.log("isDown",isDown)
					this.touchEndTop = isDown //判断 如果是首次挪动手指并且是向下移动  能激活下滑刷新
				}
				if(this.touchEndTop) { //在可刷新状态下
					this.Bscroll.disable() //禁用页面滑动
					window.PSEvent.trigger('verticalPllDown', puttDownY) // 发送事件给其他组件 在可刷新状态
				}
				this.touchTime++ //本次touch事件中手指挪动次数
				// this.$store.commit('cjy/CHANGE_PAGE_POS_Y', -pos.y)
				this.$store.commit("lxn/setPagePositionY",this.touchTime)
			},

			// 手指滑动结束
			touchEnd(event) {		
				// 如果已激活下滑刷新
				if(this.touchEndTop) {
					event && event.stopPropagation()
					event && event.preventDefault() //touch结束时阻止 点击事件发生
					this.Bscroll.enable() // touch事件结束时重新激活 滑动
				}
				// 手指滑动距离 超过0 结束时将事件发送出去
				if(this.puttDownY > 0 && this.touchEndTop) {
					var puttDownY = this.puttDownY
					this.$emit('pullDown', puttDownY)
					window.PSEvent.trigger('verticalPllDownEnd', puttDownY)
				}
				this.puttDownY = 0 // 重新初始化滑动的距离

				//当手指离开时判断是否是在最顶端
				if(this.Asss === -0 ||this.Asss === 0) {
					// console.log("this.scrollY888888",this.Asss )
					this.isTop = true
				}
			},
			//下拉刷新加载
			dataRefresh() {
				console.log("下拉")
				if(this.flagfresh) {
					this.flagfresh = false
					this.getactData(true);
					this.getTemplate()
					this.queryCoupons3();
				}
				setTimeout(() => {
					this.flagfresh = true
					window.PSEvent.trigger('pageLoadedOver')
					this.Bscroll.enable()
				}, 1200)
			},
			//记录位置
			scolllocation(pos) {
				if(-pos.y == NaN) {
					return
				}
				this.$store.commit('cjy/CHANGE_PAGE_POS_Y', -pos.y)
				this.scrollY = -pos.y
				if(pos.y == 0) {
					this.isTop = true
				} else {
					this.isTop = false
				}
			},
			//获取当前模板信息
			getTemplate() {
				let url = api.base_host + '/common/selectTemplateByStoreCode/' + this.storeCodedata;
				let config = {
					url: url,
					method: 'GET',
					headers: {
						sessionId: localStorage.getItem('sessionId')
					}
				};
				axios(config).then((res) => {
					console.log('55555555555', res)
				});
			},
			//取缓存的数据来请求数据
			getactData(isRefresh = false) {
				initData(isRefresh);
			}
		},
		created() {
			window.PSEvent.listen('dataRefresh', this.dataRefresh)
		},
		mounted() {
			this.isShare = this.$route.query.share;
			this.queryCoupons3();
			setTimeout(() => {
				this.createdScroll();
			},300)
			// this.createdScroll();
			this.inite();
			this.getsessionIddata();
			this.getactData();
			if(this.isShare == 1 && this.Title) {
				document.getElementsByTagName("title")[0].innerText = this.Title
			}
			this.$store.commit('cjy/CHANGE_PAGE_POS_Y', 0) //初始化滚轮位置
			if(this.$store.state.cjy.isReturn && this.env === "production") {
				var pageName = this.$route.name // 获取路由名称
				var pagePositionDate = this.$store.state.cjy.returnPos || {} // 获取位置存贮信息列表
				var pagePosy = pagePositionDate[pageName] ? pagePositionDate[pageName].returnPosy : 0 //找出对应的位置信息
				this.gotoPosition(pagePosy)
			}
		},
		updated() {
			this.$nextTick(() => {
				if(this.Bscroll) {
					setTimeout(() => {
						this.Bscroll.refresh()
					}, 500)
				}
			});
		},
		beforeDestroy() {
			this.removeListen()
			this.setTimeout && clearTimeout(this.setTimeout) // 清除定时器
			this.Bscroll && this.Bscroll.destroy() // 销毁Bscroll
			this.$emit('savePos', this.scrollY) //将当前的滚动位置传回父组件
		},
		beforeRouteLeave(to, from, next) {
			var name = from.name;
			this.$store.commit('cjy/SET_RETURN_POS', name);
			this.$store.commit('xxy/setacttabindex', this.tabindex);
			let ToName = to.name;
			this.$store.commit('lxn/setPageNameInfo', ToName);
			next();
		},
		watch: {
			scrollTop(newVal){
			},
			$route () {
				let PageNameInfo = this.$store.getters['lxn/getPageNameInfo'] || []
				let PagePositionY = this.$store.getters["lxn/getPagePositionY"]
				let pageName = this.$route.name
				PageNameInfo.map((item,index)=>{
					if(item===pageName){
						this.Bscroll.startY = 0
						this.createdScroll();
					}else{
						var pagePositionDate = this.$store.state.cjy.returnPos || {} // 获取位置存贮信息列表
						var pagePosy = pagePositionDate[pageName] ? -this.Asss : 0 //找出对应的位置信息
						this.gotoPosition(pagePosy)
					}
				})
				this.getactData();
			},
			scrollY(newVal){
				console.log(newVal,"newVal")
			},
		}
	}
</script>
<style>
	/* .home-container {
		overflow-y: hidden;
	} */
	
	.sbbjclass {
		position: relative;
		width: 100%;
		display: flex;
		flex-flow: column wrap;
		-webkit-flex-flow: column wrap;
		height: 100%;
		-webkit-overflow-scrolling: auto;
	}
	
	.contentnew {
		flex: 1;
		-webkit-flex: 1;
		overflow-y: auto;
		width: 100%;
		overflow-x: hidden;
	}
	
	.tabshow {
		position: absolute;
		z-index: -3;
	}
	
	.NewThematicActivities .cjy-center {
		top: 0px !important;
	}
</style>